{% extends "base_auth.html" %}

{% block title %}登录 - {{ app_name }}{% endblock %}

{% block extra_css %}
<style>
    /* 动态背景效果 */
    .dynamic-bg {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 25%, #f093fb 50%, #f5576c 75%, #667eea 100%);
        background-size: 400% 400%;
        animation: gradientShift 15s ease infinite;
        z-index: -2;
    }
    
    @keyframes gradientShift {
        0% { background-position: 0% 50%; }
        50% { background-position: 100% 50%; }
        100% { background-position: 0% 50%; }
    }
    
    /* 浮动几何图形 */
    .floating-shapes {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: -1;
    }
    
    .shape {
        position: absolute;
        border-radius: 50%;
        background: rgba(102, 126, 234, 0.15);
        animation: float 20s infinite linear;
    }
    
    .shape:nth-child(1) {
        width: 80px; height: 80px; top: 20%; left: 10%;
        animation-delay: 0s; animation-duration: 25s;
    }
    .shape:nth-child(2) {
        width: 120px; height: 120px; top: 60%; left: 80%;
        animation-delay: 5s; animation-duration: 30s;
    }
    .shape:nth-child(3) {
        width: 60px; height: 60px; top: 80%; left: 20%;
        animation-delay: 10s; animation-duration: 20s;
    }
    .shape:nth-child(4) {
        width: 100px; height: 100px; top: 10%; left: 70%;
        animation-delay: 15s; animation-duration: 35s;
    }
    .shape:nth-child(5) {
        width: 40px; height: 40px; top: 40%; left: 50%;
        animation-delay: 20s; animation-duration: 15s;
    }
    
    @keyframes float {
        0% { transform: translateY(0px) rotate(0deg); opacity: 0.7; }
        25% { transform: translateY(-20px) rotate(90deg); opacity: 0.5; }
        50% { transform: translateY(-40px) rotate(180deg); opacity: 0.3; }
        75% { transform: translateY(-20px) rotate(270deg); opacity: 0.5; }
        100% { transform: translateY(0px) rotate(360deg); opacity: 0.7; }
    }
    
    /* 粒子效果 */
    .particles {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        z-index: -1;
    }
    
    .particle {
        position: absolute;
        width: 4px;
        height: 4px;
        background: rgba(102, 126, 234, 0.8);
        border-radius: 50%;
        animation: particleFloat 10s infinite linear;
    }
    
    .particle:nth-child(1) { top: 10%; left: 20%; animation-delay: 0s; }
    .particle:nth-child(2) { top: 20%; left: 80%; animation-delay: 2s; }
    .particle:nth-child(3) { top: 60%; left: 10%; animation-delay: 4s; }
    .particle:nth-child(4) { top: 80%; left: 90%; animation-delay: 6s; }
    .particle:nth-child(5) { top: 30%; left: 60%; animation-delay: 8s; }
    .particle:nth-child(6) { top: 70%; left: 40%; animation-delay: 1s; }
    .particle:nth-child(7) { top: 50%; left: 30%; animation-delay: 3s; }
    .particle:nth-child(8) { top: 90%; left: 70%; animation-delay: 5s; }
    
    @keyframes particleFloat {
        0% { transform: translateY(0px) translateX(0px); opacity: 0; }
        10% { opacity: 1; }
        90% { opacity: 1; }
        100% { transform: translateY(-100vh) translateX(50px); opacity: 0; }
    }
    
    /* 波浪效果 */
    .wave {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100px;
        background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1200 120' preserveAspectRatio='none'%3E%3Cpath d='M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z' fill='rgba(102, 126, 234, 0.15)'/%3E%3C/svg%3E");
        background-size: cover;
        animation: wave 10s linear infinite;
        z-index: -1;
    }
    
    @keyframes wave {
        0% { transform: translateX(0); }
        100% { transform: translateX(-1200px); }
    }
    
    .floating {
        animation: floating 3s ease-in-out infinite;
    }
    
    @keyframes floating {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
    }
    
    .slide-in {
        animation: slideIn 0.5s ease-out;
    }
    
    @keyframes slideIn {
        from { opacity: 0; transform: translateY(30px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    /* 错误提示样式 */
    .error-message {
        background-color: rgba(231, 76, 60, 0.1);
        border-left: 4px solid #e74c3c;
        color: #e74c3c;
        padding: 12px 16px;
        border-radius: 4px;
        margin-bottom: 16px;
        font-size: 14px;
        display: none;
    }
    
    .error-message.show {
        display: block;
        animation: shake 0.5s ease-in-out;
    }
    
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-5px); }
        75% { transform: translateX(5px); }
    }
    
    /* 成功提示样式 */
    .success-message {
        background-color: rgba(39, 174, 96, 0.1);
        border-left: 4px solid #27ae60;
        color: #27ae60;
        padding: 12px 16px;
        border-radius: 4px;
        margin-bottom: 16px;
        font-size: 14px;
        display: none;
    }
    
    .success-message.show {
        display: block;
        animation: slideIn 0.5s ease-out;
    }
</style>
{% endblock %}

{% block content %}
<!-- 动态背景层 -->
<div class="dynamic-bg"></div>

<!-- 浮动几何图形 -->
<div class="floating-shapes">
    <div class="shape"></div>
    <div class="shape"></div>
    <div class="shape"></div>
    <div class="shape"></div>
    <div class="shape"></div>
</div>

<!-- 粒子效果 -->
<div class="particles">
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
    <div class="particle"></div>
</div>

<!-- 波浪效果 -->
<div class="wave"></div>

<!-- 主要内容 -->
<div class="min-h-screen flex items-center justify-center relative overflow-hidden">
    <!-- 背景装饰层 -->
    <div class="absolute inset-0 overflow-hidden">
        <div class="absolute -top-40 -right-40 w-80 h-80 rounded-full opacity-20 blur-3xl" style="background-color: #667eea;"></div>
        <div class="absolute -bottom-40 -left-40 w-80 h-80 rounded-full opacity-20 blur-3xl" style="background-color: #764ba2;"></div>
    </div>
    
    <!-- 登录容器 -->
    <div class="relative z-10 w-full max-w-md mx-4">
        <div class="glass-effect rounded-2xl shadow-2xl p-8 slide-in">
            <!-- Logo和标题 -->
            <div class="text-center mb-8">
                <div class="w-20 h-20 mx-auto mb-4 rounded-2xl gradient-bg flex items-center justify-center floating">
                    <i class="fas fa-file-contract text-white text-3xl"></i>
                </div>
                <h1 class="text-3xl font-bold gradient-text mb-2">{{ app_name }}</h1>
                <p class="text-slate-600">智能信访分析平台</p>
            </div>
            
            <!-- 登录表单 -->
            <form id="loginForm" class="space-y-6">
                <!-- 错误提示信息 -->
                <div id="errorMessage" class="error-message">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <span id="errorText">账号或密码错误</span>
                </div>
                
                <!-- 成功提示信息 -->
                <div id="successMessage" class="success-message">
                    <i class="fas fa-check-circle mr-2"></i>
                    <span id="successText">登录成功</span>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">用户名</label>
                    <div class="relative">
                        <i class="fas fa-user absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
                        <input type="text" id="username" class="w-full pl-10 pr-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入用户名" required>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-2">密码</label>
                    <div class="relative">
                        <i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
                        <input type="password" id="password" class="w-full pl-10 pr-12 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" placeholder="请输入密码" required>
                        <button type="button" id="togglePassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                
                <!-- 记住密码和忘记密码 -->
                <div class="flex items-center justify-between">
                    <label class="flex items-center">
                        <input type="checkbox" id="rememberMe" class="w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500">
                        <span class="ml-2 text-sm text-slate-600">记住密码</span>
                    </label>
                    <a href="#" id="forgotPassword" class="text-sm text-blue-600 hover:text-blue-800">忘记密码？</a>
                </div>
                
                <!-- 登录按钮 -->
                <button type="submit" class="w-full gradient-bg text-white py-3 rounded-lg font-medium hover:shadow-lg transform hover:scale-[1.02] transition-all duration-200">
                    登录系统
                </button>
            </form>
            
            <!-- 分割线 -->
            <div class="relative my-6">
                <div class="absolute inset-0 flex items-center">
                    <div class="w-full border-t border-slate-300"></div>
                </div>
                <div class="relative flex justify-center text-sm">
                    <span class="px-2 bg-white text-slate-500">或</span>
                </div>
            </div>
            
            <!-- 快速登录 -->
            <div class="text-center">
                <p class="text-sm text-slate-600 mb-4">快速登录</p>
                <div class="flex justify-center space-x-4">
                    <button class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center hover:bg-blue-200 transition-colors">
                        <i class="fab fa-weixin text-green-600 text-xl"></i>
                    </button>
                    <button class="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center hover:bg-slate-200 transition-colors">
                        <i class="fas fa-fingerprint text-slate-600 text-xl"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 版权信息 -->
        <div class="text-center mt-6 text-sm text-slate-500">
            <p>&copy; 2024 博沃智慧. All rights reserved.</p>
        </div>
    </div>
    
    <!-- 忘记密码模态框 -->
    <div id="forgotPasswordModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl p-8 max-w-md w-full mx-4 slide-in">
            <h3 class="text-xl font-bold text-slate-800 mb-4">找回密码</h3>
            <p class="text-slate-600 mb-6">请输入您的邮箱地址，我们将发送验证码给您</p>
            
            <form id="forgotPasswordForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-slate-700 mb-2">邮箱地址</label>
                    <div class="relative">
                        <i class="fas fa-envelope absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
                        <input type="email" id="email" class="w-full pl-10 pr-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="请输入邮箱" required>
                    </div>
                </div>
                
                <div class="mb-6">
                    <label class="block text-sm font-medium text-slate-700 mb-2">验证码</label>
                    <div class="flex space-x-2">
                        <input type="text" id="verifyCode" class="flex-1 px-4 py-3 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="请输入验证码" required>
                        <button type="button" id="sendCode" class="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors">
                            发送验证码
                        </button>
                    </div>
                </div>
                
                <div class="flex space-x-3">
                    <button type="button" id="cancelReset" class="flex-1 px-4 py-3 border border-slate-300 rounded-lg hover:bg-slate-50 transition-colors">
                        取消
                    </button>
                    <button type="submit" class="flex-1 gradient-bg text-white py-3 rounded-lg hover:shadow-lg transition-all">
                        重置密码
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 全局变量
    let loginAttempts = 0;
    const MAX_LOGIN_ATTEMPTS = 5;
    const LOCKOUT_DURATION = 30 * 60 * 1000; // 30分钟锁定时间
    
    // 检查登录锁定状态
    function checkLoginLock() {
        // 开发环境自动解锁
        if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
            localStorage.removeItem('loginLockUntil');
        }
        const lockUntil = localStorage.getItem('loginLockUntil');
        if (lockUntil && new Date().getTime() < parseInt(lockUntil)) {
            const remainingTime = Math.ceil((parseInt(lockUntil) - new Date().getTime()) / 60000);
            showError(`登录尝试次数过多，请${remainingTime}分钟后再试`);
            return true;
        }
        return false;
    }
    
    // 更新登录锁定状态
    function updateLoginLock() {
        loginAttempts++;
        if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
            const lockUntil = new Date().getTime() + LOCKOUT_DURATION;
            localStorage.setItem('loginLockUntil', lockUntil.toString());
            showError(`登录失败次数过多，账户已锁定30分钟`);
            return true;
        }
        return false;
    }
    
    // 重置登录尝试次数
    function resetLoginAttempts() {
        loginAttempts = 0;
        localStorage.removeItem('loginLockUntil');
    }
    
    // 显示错误信息
    function showError(message) {
        const errorMessage = document.getElementById('errorMessage');
        const errorText = document.getElementById('errorText');
        const successMessage = document.getElementById('successMessage');
        
        errorText.textContent = message;
        errorMessage.classList.add('show');
        successMessage.classList.remove('show');
        
        // 3秒后自动隐藏错误信息
        setTimeout(() => {
            errorMessage.classList.remove('show');
        }, 3000);
    }
    
    // 显示成功信息
    function showSuccess(message) {
        const successMessage = document.getElementById('successMessage');
        const successText = document.getElementById('successText');
        const errorMessage = document.getElementById('errorMessage');
        
        successText.textContent = message;
        successMessage.classList.add('show');
        errorMessage.classList.remove('show');
        
        // 2秒后自动隐藏成功信息
        setTimeout(() => {
            successMessage.classList.remove('show');
        }, 2000);
    }
    
    // 密码显示/隐藏切换
    const togglePassword = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');
    
    togglePassword.addEventListener('click', () => {
        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
        passwordInput.setAttribute('type', type);
        togglePassword.innerHTML = type === 'password' ? '<i class="fas fa-eye"></i>' : '<i class="fas fa-eye-slash"></i>';
    });
    
    // 忘记密码模态框
    const forgotPassword = document.getElementById('forgotPassword');
    const forgotPasswordModal = document.getElementById('forgotPasswordModal');
    const cancelReset = document.getElementById('cancelReset');
    
    forgotPassword.addEventListener('click', (e) => {
        e.preventDefault();
        forgotPasswordModal.classList.remove('hidden');
    });
    
    cancelReset.addEventListener('click', () => {
        forgotPasswordModal.classList.add('hidden');
    });
    
    // 点击模态框外部关闭
    forgotPasswordModal.addEventListener('click', (e) => {
        if (e.target === forgotPasswordModal) {
            forgotPasswordModal.classList.add('hidden');
        }
    });
    
    // 发送验证码倒计时
    const sendCode = document.getElementById('sendCode');
    let countdown = 60;
    
    sendCode.addEventListener('click', async () => {
        if (countdown === 60) {
            const email = document.getElementById('email').value;
            
            if (!email) {
                alert('请先输入邮箱地址');
                return;
            }
            
            try {
                sendCode.disabled = true;
                sendCode.textContent = '发送中...';
                
                // 模拟发送验证码API调用
                const response = await simulateSendCodeAPI(email);
                
                if (response.success) {
                    showSuccess('验证码已发送到您的邮箱');
                    
                    // 开始倒计时
                    const timer = setInterval(() => {
                        countdown--;
                        sendCode.textContent = `${countdown}秒后重发`;
                        if (countdown <= 0) {
                            clearInterval(timer);
                            sendCode.textContent = '发送验证码';
                            sendCode.disabled = false;
                            countdown = 60;
                        }
                    }, 1000);
                } else {
                    alert(response.message || '验证码发送失败');
                    sendCode.textContent = '发送验证码';
                    sendCode.disabled = false;
                }
            } catch (error) {
                console.error('发送验证码错误:', error);
                alert('验证码发送过程中发生错误，请稍后重试');
                sendCode.textContent = '发送验证码';
                sendCode.disabled = false;
            }
        }
    });
    
    // 模拟发送验证码API调用
    async function simulateSendCodeAPI(email) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟邮箱格式验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return {
                success: false,
                message: '邮箱格式不正确'
            };
        }
        
        return {
            success: true,
            message: '验证码发送成功'
        };
    }
    
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        // 检查登录锁定状态
        if (checkLoginLock()) {
            return;
        }
        
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        
        if (!username || !password) {
            showError('请输入用户名和密码');
            return;
        }
        
        // 禁用登录按钮，防止重复提交
        const submitButton = loginForm.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;
        submitButton.disabled = true;
        submitButton.textContent = '登录中...';
        
        try {
            // 构建登录数据（不加密，由后端处理）
            const loginData = {
                username: username,
                password: password
            };
            
            console.log('正在调用登录API...');
            
            // 调用真实的登录API
            const response = await callLoginAPI(loginData);
            
            if (response.success) {
                // 登录成功
                resetLoginAttempts();
                showSuccess('登录成功，正在跳转...');
                
                // 使用authManager保存token
                window.authManager.saveToken(
                    response.access_token,
                    null,  // 暂时不使用refresh_token
                    response.expires_in
                );
                
                // 使用authManager处理重定向
                setTimeout(() => {
                    window.authManager.handleLoginSuccess();
                }, 1500);
            } else {
                // 登录失败
                if (updateLoginLock()) {
                    return; // 账户已锁定
                }
                showError(response.message || '账号或密码错误');
            }
        } catch (error) {
            console.error('登录错误:', error);
            if (error.response && error.response.status === 401) {
                showError('账号或密码错误');
            } else if (error.response && error.response.status === 403) {
                showError('用户已被禁用');
            } else {
                showError('网络连接失败，请检查网络设置');
            }
        } finally {
            // 恢复登录按钮状态
            submitButton.disabled = false;
            submitButton.textContent = originalText;
        }
    });
    
    // 真实登录API调用
    async function callLoginAPI(loginData) {
        try {
            // 使用Web登录接口
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(loginData)
            });
            
            if (response.ok) {
                // 登录成功，服务器返回重定向
                const data = await response.json();
                return {
                    success: true,
                    message: '登录成功',
                    access_token: data.access_token,
                    refresh_token: null,  // 暂时不使用refresh_token
                    expires_in: data.expires_in || 1800  // 默认30分钟
                };
            } else {
                // 登录失败，返回错误页面
                const text = await response.text();
                return {
                    success: false,
                    message: '用户名或密码错误',
                    access_token: null
                };
            }
        } catch (error) {
            console.error('API调用错误:', error);
            // 重新抛出错误，让上层处理
            throw error;
        }
    }
    
    // 页面加载时检查记住的用户名
    window.addEventListener('load', () => {
        // 注意：在登录页面不检查已登录状态，避免无限循环
        // 如果用户确实已登录，他们会通过其他页面访问，而不是直接访问登录页面
        
        // 检查记住的用户名
        const rememberedUsername = window.authManager.getRememberedUsername();
        if (rememberedUsername) {
            document.getElementById('username').value = rememberedUsername;
            document.getElementById('rememberMe').checked = true;
        }
        
        // 检查登录锁定状态
        checkLoginLock();
    });
    
    // 忘记密码表单提交
    const forgotPasswordForm = document.getElementById('forgotPasswordForm');
    forgotPasswordForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const email = document.getElementById('email').value;
        const verifyCode = document.getElementById('verifyCode').value;
        
        if (!email || !verifyCode) {
            alert('请填写邮箱地址和验证码');
            return;
        }
        
        try {
            // 模拟密码重置API调用
            const response = await simulatePasswordResetAPI(email, verifyCode);
            
            if (response.success) {
                showSuccess('密码重置成功，请使用新密码登录');
                forgotPasswordModal.classList.add('hidden');
                
                // 清空表单
                document.getElementById('email').value = '';
                document.getElementById('verifyCode').value = '';
            } else {
                alert(response.message || '密码重置失败，请重试');
            }
        } catch (error) {
            console.error('密码重置错误:', error);
            alert('密码重置过程中发生错误，请稍后重试');
        }
    });
    
    // 模拟密码重置API调用
    async function simulatePasswordResetAPI(email, verifyCode) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟验证码验证（实际项目中应该由后端验证）
        const validCodes = {
            'test@example.com': '123456'
        };
        
        if (validCodes[email] === verifyCode) {
            return {
                success: true,
                message: '密码重置成功'
            };
        } else {
            return {
                success: false,
                message: '邮箱或验证码错误'
            };
        }
    }
</script>
{% endblock %}